package com.holdtime.jtt809dataservice.common.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import protocol.jtt809.JTT809Packet;
import protocol.jtt809.JTT809Util;
import protocol.jtt809.body.RawBody;

import java.util.List;

public class JTT809Decoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        boolean matched = false;
        int start = in.readerIndex();
        int limit = in.writerIndex();
        while (in.isReadable()) {
            byte b = in.readByte();
            if (!matched) {
                if (b != JTT809Packet.HEADER) continue;
                start = in.readerIndex() - 1;
                matched = true;
                continue;
            }

            if (b != JTT809Packet.TAIL) continue;
            int pos = in.readerIndex();
            in.readerIndex(start);
            in.writerIndex(pos);
            decode(in, out);
            in.writerIndex(limit);
            in.readerIndex(pos);
            return;
        }

        if (matched) {
            in.writerIndex(limit);
            in.readerIndex(start);
        }
    }

    private void decode(ByteBuf buf, List<Object> out) {
        int size = buf.writerIndex() - buf.readerIndex();
        byte[] bytes = new byte[size];
        buf.readBytes(bytes);
        byte[] data = JTT809Util.antisense(bytes);
        if (data == null || data.length == 0) return;
        JTT809Packet<RawBody> packet = new JTT809Packet<>();
        packet.setBody(new RawBody());
        packet.from(data);
        out.add(packet);
    }
}
